from fastapi import APIRouter, FastAPI, Depends, HTTPException, Form
from ..model.slave import User, Role
from ..utils.database import SessionLocal
from ..utils.post_item import AddUserItem, ModifyUserItem, DeleteUserItem, LoginUserItem, UserAllItem
import os
from passlib.context import CryptContext
from ..utils.user import my_oauth2_scheme
from sqlalchemy import func
from datetime import timedelta


router = APIRouter()

root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 密码加密
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


@router.post('/register')
async def register(item: AddUserItem):
    
    with SessionLocal() as session:
        user = session.query(User).filter_by(user_name=item.username).first()
        if user:
            return {"code": 1, "msg": "用户名已存在，请重新输入"}
        hashed_password = pwd_context.hash(item.password)
        user = User(user_name=item.username, passwd=hashed_password, role_code=item.role_code)
        session.add(user)

        session.commit()

        return {"code": 0, "msg": "创建用户成功"}
    


@router.post('/modify')
async def modify(item: ModifyUserItem):
    
    with SessionLocal() as session:
        user = session.query(User).filter_by(user_code=item.user_code).first()
        
        if item.username:
            user.user_name=item.username
        if item.password:
            hashed_password = pwd_context.hash(item.password)
            user.passwd=hashed_password
        if item.role_code:
            user.role_code=item.role_code

        session.commit()

        return {"code": 0, "msg": "修改用户成功"}
    

@router.post('/delete')
async def delete(item: DeleteUserItem):
    
    with SessionLocal() as session:
        session.query(User).filter_by(user_code=item.user_code).delete()
        session.commit()

        return {"code": 0, "msg": "删除用户成功"}
    

@router.post('/login', tags=["authentication"])
async def login(username: str = Form(...), password: str = Form(...)):

    with SessionLocal() as session:
        user = session.query(User).filter_by(user_name=username).first()
        if not user: 
            return {"code": 1, "msg": "用户名不存在，请重新输入"}
        if not pwd_context.verify(password, user.passwd):
            return {"code": 1, "msg": "密码不正确"}
      
        # 如果验证成功，创建并返回 token
        # access_token_expires = timedelta(minutes=my_oauth2_scheme.ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = my_oauth2_scheme.create_jwt_token(
            data={"user_name": user.user_name}
        )
        role_code = user.role_code
        role_name = session.query(Role).filter_by(role_code=role_code).first().role_name
        return {"code": 0, "msg": "Login successful", "username": user.user_name, "role_name": role_name, "access_token": access_token}
    


@router.post('/all')
async def all(item: UserAllItem):
    page_index = item.page_index
    page_size = item.page_size
    with SessionLocal() as session:
        offset_data = page_size * (page_index-1)
        total_num = session.query(func.count(User.id)).scalar()
        users = session.query(User).order_by(User.id.desc()).offset(offset_data).limit(page_size).all()
        res = []
        for user in users:
            role_code = user.role_code
            role_name = session.query(Role).filter_by(role_code=role_code).first().role_name
            res.append({"username": user.user_name, "role_name": role_name, "user_code": user.user_code})
        return {"data": res, "total_num": total_num}


@router.get('/role')
async def role():
    with SessionLocal() as session:
        roles = session.query(Role).all()
        res = []
        for role in roles:
            res.append({"role_code": role.role_code, "role_name": role.role_name})

        return res
    


    



